package com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.dao;

import com.skytech.tax.customsdatawarehouse.singlewindow.customsdeclarations.domain.entity.IECustomsDeclarationSimple;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 进出口关单简表（单一窗口）
 */
@Repository("singleWindow.ieCustomsDeclarationSimpleDao")
public class IECustomsDeclarationSimpleDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String saveCustomsDeclarationSimpleSql = "INSERT INTO gd_jckhwgd_simple (cusCiqNo, updateTime, cusDecStatus) VALUES (:cusCiqNo, :updateTime, :cusDecStatus)";

    public void save(IECustomsDeclarationSimple customsDeclarationSimple) {
        namedParameterJdbcTemplate.update(this.saveCustomsDeclarationSimpleSql, new BeanPropertySqlParameterSource(customsDeclarationSimple));
    }

    private String existsCustomsDeclarationSimpleSql = "SELECT count(1) FROM gd_jckhwgd_simple WHERE cusCiqNo = ? AND updateTime = ?";

    public boolean exists(String cusCiqNo, String updateTime, String cusDecStatus) {
        StringBuilder builder = new StringBuilder(existsCustomsDeclarationSimpleSql);
        Object[] params = new Object[]{cusCiqNo, updateTime};
        if (StringUtils.isNotBlank(cusDecStatus)) {
            builder.append(" and cusDecStatus = ?");
            params = new Object[]{cusCiqNo, updateTime, cusDecStatus};
        }
        return Boolean.TRUE.equals(namedParameterJdbcTemplate.getJdbcOperations()
                .queryForObject(builder.toString(), params, boolean.class));
    }

    private String deleteCustomsDeclarationSimpleSql = "DELETE FROM gd_jckhwgd_simple WHERE cusCiqNo = ?";

    public void delete(String cusCiqNo) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteCustomsDeclarationSimpleSql, cusCiqNo);
    }

    private String existsCustomsDeclarationsSimpleSql = "SELECT cusCiqNo AS exist FROM gd_jckhwgd_simple WHERE (cusCiqNo, updateTime, cusDecStatus) in (%s) GROUP BY cusCiqNo";

    public List<String> exists(List<IECustomsDeclarationSimple> simpleList) {
        List<String> params = new ArrayList<>();
        simpleList.forEach(item -> params.add("('" + item.getCusCiqNo() + "','" + item.getUpdateTime() + "','" + item.getCusDecStatus() + "')"));
        String sql = String.format(this.existsCustomsDeclarationsSimpleSql, StringUtils.join(params, ","));
        return this.namedParameterJdbcTemplate.getJdbcOperations().queryForList(sql, String.class);
    }
}
